<?php

/**
 * 使用长连接方式连接swoole
 * @param $hosts
 * @param $port
 * @param $data
 * @return mixed
 */
function connectSwoole($hosts, $port, $data) {
    // 使用长连接方式连接swoole
    $client = new \swoole_client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);

    // 连接到服务器
    $client->connect($hosts, $port);

    // 向服务器发送数据
    $client->send($data);

    // 接收服务器返回数据
    $res = $client->recv();

    // 关闭连接
    $client->close(true);

    return $res;
}

/**
 * 无状态异步消息处理
 * @param $taskData
 * @return mixed
 */
function stateLessAsyncTask($taskData) {

    $hosts = "127.0.0.1";
    $port = "9502";

    return connectSwoole($hosts, $port, json_encode($taskData));

}

/**
 * 异步消息处理
 * @param $missionCode
 * @return mixed
 */
function asyncTask($missionCode) {

    $hosts = "127.0.0.1";
    $port = "9501";

    return connectSwoole($hosts, $port, $missionCode);

}

/**
 * 延迟任务
 * @param $executeTime
 * @param $missionCode
 * @return mixed
 */
function setTimeoutTask($executeTime, $missionCode) {

    $hosts = "127.0.0.1";
    $port = "9509";

    $data = json_encode([
        "execute_time" => $executeTime,
        "mission_code" => $missionCode
    ]);

    return connectSwoole($hosts, $port, $data);


}